//src/components/ToolKit/DBConnEnv.tsx
import React from "react";
import { Card, Col, Input, Button, Space, message } from "antd";
import { 
  DatabaseOutlined, 
  PlayCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  PlusOutlined,
  MinusOutlined
} from "@ant-design/icons";
import { useStore } from '../../stores';
import { observer } from "mobx-react-lite";
import * as styles from '../../assets/styles/toolkit/environment.module';
import EditableTitle from './EditableTitle';

// 定义数据库配置类型
interface DbConfig {
  host: string;
  port: string;
  database: string;
  username: string;
  password: string;
}

// 定义数据库卡片类型
interface DbCard {
  id: number;
  name: string;
  config: DbConfig;
  isConnected: boolean;
}

interface DBConnEnvProps {
  card: DbCard;
  onFormChange: (id: number, field: string, value: string) => void;
  onRemoveCard: (id: number) => void;
  onAddNewCard: () => void;
  onTestConnection: (id: number) => void;
  onDbNameSave: (id: number, name: string) => void;
  isValidIP: (host: string) => boolean;
  isFormValid: (config: DbConfig) => boolean;
}

const DBConnEnv: React.FC<DBConnEnvProps> = observer(({
  card,
  onFormChange,
  onRemoveCard,
  onAddNewCard,
  onTestConnection,
  onDbNameSave,
  isValidIP,
  isFormValid
}) => {
  const store = useStore();
  const dbCards = store.toolkit.dbCards;
  
  // 处理测试连接
  const handleTestConnection = async (id: number) => {
    // 执行测试连接
    onTestConnection(id);
    
    // 使用轮询方式检查连接状态，最多尝试10次，每次间隔50ms
    const maxAttempts = 10;
    const checkConnectionStatus = async (attempt = 0) => {
      const updatedCard = store.toolkit.dbCards.find(c => c.id === id);
      
      if (updatedCard && updatedCard.isConnected) {
        // 连接成功，移除已连接的卡片
        store.toolkit.removeConnectedDbCard(id);
        message.success('数据库连接成功');
        return;
      }
      
      // 如果未连接且未达到最大尝试次数，继续轮询
      if (attempt < maxAttempts - 1) {
        setTimeout(() => checkConnectionStatus(attempt + 1), 50);
      } else if (updatedCard && !updatedCard.isConnected) {
        // 达到最大尝试次数但仍未连接成功
        message.error('数据库连接失败，请检查配置信息');
      }
    };
    
    // 开始检查连接状态
    checkConnectionStatus();
  };
  
  return (
    <Col span={12} key={card.id}>
      <Card 
        title={
          <EditableTitle 
            title={card.name}
            icon={<DatabaseOutlined />}
            onSave={(name) => onDbNameSave(card.id, name)}
          />
        }
        extra={
          <div style={{ display: 'flex', gap: '4px' }}>
            {/* 减号圆形按钮--删除数据库卡片 */}
            {dbCards.length > 1 && (
              <Button 
                type="primary" 
                shape="circle" 
                icon={<MinusOutlined />} 
                onClick={() => onRemoveCard(card.id)}
                size="small"
                style={{ opacity: 0, transition: 'opacity 0.3s',backgroundColor: '#682424' }}
                className="remove-button"
              />
            )}
            {dbCards.length === 1 && (
              <Button 
                type="primary" 
                onClick={(e) => {
                  e.stopPropagation();
                  onAddNewCard();
                }}
                size="small"
                style={{ 
                  marginLeft: 'auto', 
                  color: 'white', 
                  alignSelf: 'flex-end', 
                  backgroundColor: '#515251',
                  transition: 'opacity 0.3s'
                }}
                className="fixed-add-button"
              >
                新增配置卡片
              </Button>
            )}
            {dbCards.length > 1 && (
              <Button 
                type="primary" 
                shape="circle" 
                icon={<PlusOutlined />} 
                onClick={onAddNewCard}
                size="small"
                style={{ opacity: 0, transition: 'opacity 0.3s',backgroundColor: '#294F1F' }}
                className="add-button"
              />
            )}
          </div>
        }
        onMouseEnter={(e) => {
          const addButton = e.currentTarget.querySelector('.add-button') as HTMLElement;
          if (addButton) {
            addButton.style.opacity = '1';
          }
          const removeButton = e.currentTarget.querySelector('.remove-button') as HTMLElement;
          if (removeButton) {
            removeButton.style.opacity = '1';
          }
        }}
        onMouseLeave={(e) => {
          const addButton = e.currentTarget.querySelector('.add-button') as HTMLElement;
          if (addButton) {
            addButton.style.opacity = '0';
          }
          const removeButton = e.currentTarget.querySelector('.remove-button') as HTMLElement;
          if (removeButton) {
            removeButton.style.opacity = '0';
          }
        }}
      >
        <div className={styles.formItem}>
          <label className={styles.formLabel}>
            主机地址<span style={{ color: 'red' }}>*</span>
          </label>
          <Input 
            value={card.config.host}
            onChange={e => onFormChange(card.id, 'host', e.target.value)}
            placeholder="core-db.example.com"
          />
        </div>
        
        <div className={styles.formItem}>
          <label className={styles.formLabel}>
            端口
            {isValidIP(card.config.host) && <span style={{ color: 'red' }}>*</span>}
          </label>
          <Input 
            value={card.config.port}
            onChange={e => onFormChange(card.id, 'port', e.target.value)}
            placeholder="3306"
          />
        </div>
        
        <div className={styles.formItem}>
          <label className={styles.formLabel}>
            数据库名<span style={{ color: 'red' }}>*</span>
          </label>
          <Input 
            value={card.config.database}
            onChange={e => onFormChange(card.id, 'database', e.target.value)}
            placeholder="production_db"
          />
        </div>
        
        <div className={styles.formItem}>
          <label className={styles.formLabel}>
            用户名<span style={{ color: 'red' }}>*</span>
          </label>
          <Input 
            value={card.config.username}
            onChange={e => onFormChange(card.id, 'username', e.target.value)}
            placeholder="admin"
          />
        </div>
        
        <div className={styles.formItem}>
          <label className={styles.formLabel}>
            密码<span style={{ color: 'red' }}>*</span>
          </label>
          <Input.Password 
            value={card.config.password}
            onChange={e => onFormChange(card.id, 'password', e.target.value)}
            placeholder="password"
          />
        </div>
        
        <div className={styles.formItem}>
          <Space>
            <Button 
              type="primary" 
              icon={<PlayCircleOutlined />}
              onClick={() => handleTestConnection(card.id)}
              disabled={!isFormValid(card.config)}
            >
              测试连接
            </Button>
            {card.isConnected ? (
              <span className={styles.connectionStatus}>
                <CheckCircleOutlined className={styles.connected} />
                <span className={styles.connected}>已连接</span>
              </span>
            ) : (
              <span className={styles.connectionStatus}>
                <CloseCircleOutlined className={styles.disconnected} />
                <span className={styles.disconnected}>未连接</span>
              </span>
            )}
          </Space>
        </div>
      </Card>
    </Col>
  );
});

export default DBConnEnv;